<?php
/**
 * Only loaded with upload widget: if "browse_button" id does not exist, fails!
 */
?>
$(document).ready(function() {
    var uploader = new plupload.Uploader({
	        runtimes : 'flash,gears,silverlight,html5,browserplus',
	        browse_button : 'uploadfiles',
	        max_file_size : '10mb',
	        url : '<?=$upload_action_url;?>',
	        flash_swf_url : '<?=$plupload_flash_swf;?>',
	        silverlight_xap_url : '<?=$plupload_silverlight_xap;?>',
	        filters : [
	            {title : "Image files", extensions : "jpg,gif,png"},
	            {title : "Zip files", extensions : "zip"}
	        ],
	        resize : {width : 800, height : 800, quality : 95}
	    });

    uploader.bind('Init', function(up, params) {
        $('#throbber').hide();
        $('#pluploader').hide();
        $('#plcontainer.runtime').html("<div>Current runtime: " + params.runtime + "</div>");
    });
    uploader.bind('StateChanged', function(up) {
        if (up.state==plupload.STARTED) $('#throbber').show();
        else if (up.state==plupload.STOPPED) $('#throbber').hide();
    });
    uploader.bind('FileUploaded', function(up, file, response) {
        reloadFileList();
    });
    uploader.bind('QueueChanged', function(up) {
        uploader.start();
    });
    uploader.init();


    // --------------------------------------------------------------- File list
    function reloadFileList() {
        // Update #fileList
        $('#fileList').load("<?=$file_list_url;?> #fileList", {
                dragHandle:true,
                entity:'<?=get_class($this->model);?>' // entity
                <?php
                $modelId = $this->model->getPrimaryKey();
                print isset($modelId) ? ',EXid:'.$modelId : ',EXid:0';
                ?>
            },
            registerFileListLinks
        );
    }
    function registerFileListLinks(evt) {
        $('#fileList a.delete').click(function() {
            var params = new Object();
            if ($(this).attr('fid')!==undefined) params.fid=$(this).attr('fid');
            if ($(this).attr('sid')!==undefined) params.sid=$(this).attr('sid');
            $.getJSON('<?=$delete_action_url;?>', params,
                function(json) { if (json.result==0) reloadFileList(); }
            );
            return false;
        });
        // DnD
        $('#dragTable').tableDnD({
          onDrop: function(table, row) {
            $("#dragTable .weight").each(function(index) {
              this.value = index;
            });
          },
          dragHandle: "dragHandle"
        });
        // Plupload
        uploader.refresh();
    }
    registerFileListLinks();


});
